package org.sensation.server.file.transfer;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.sensation.server.file.transfer.dispachservice.DispacheService;
import org.sensation.server.file.transfer.dispachservice.ReadService;
import org.sensation.server.file.transfer.dispachservice.WriteService;
import org.sensation.server.file.transfer.request.FileChannelRequest;

public class SelectedKeyDispacheService {
	private Map<Integer, DispacheService> dispacheServices;
	
	public SelectedKeyDispacheService() {
		super();
		setupDispatchService();
	}
	
	public void dispatchService(Iterator<SelectionKey> keys)
			throws IOException {
		while (keys.hasNext()) {
			SelectionKey key = keys.next();
			DispacheService dispacheService = selectedKeyDispatch(key);
			
			FileChannelRequest request = new FileChannelRequest(key);
			dispacheService.service(request);
			keys.remove();
		}
	}
	
	private void setupDispatchService() {
		this.dispacheServices = new HashMap<Integer, DispacheService>();
		dispacheServices.put(SelectionKey.OP_READ, new ReadService());
		dispacheServices.put(SelectionKey.OP_WRITE, new WriteService());
	}
	
	private DispacheService selectedKeyDispatch(SelectionKey key) throws IOException {
		return dispacheServices.get(key.interestOps());
	}
}
